package network.connectionpool;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;

public class ConnectionPoolImpl implements ConnectionPool{

	private final String url = "jdbc:mysql://localhost:3306/STOREDB";
	private final String user = "root";
	private final String password = "123456";
	
	private final ArrayList<Connection> pool = new ArrayList<Connection>();
	
	private int poolSize = 5;
	
	static{
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			System.out.println("MySQL数据库驱动加载失败");
			e.printStackTrace();
		}
	}
	
	public ConnectionPoolImpl() {
	}
	
	public ConnectionPoolImpl(int poolSize){
		this.poolSize = poolSize;
	}
	
	@Override
	public Connection getConnection() throws SQLException {
		synchronized(pool){
			if(!pool.isEmpty()){
				int last = pool.size() - 1;
				Connection conn = pool.remove(last);
				return conn;
			}
			Connection conn = DriverManager.getConnection(url,user,password);
			return conn;
		}
	}

	@Override
	public void releaseConnection(Connection conn) throws SQLException {
		synchronized(pool){
			int current = pool.size();
			if(current < poolSize){
				pool.add(conn);
				return;
			}
			try{
				conn.close();
			}catch(SQLException e){
				e.printStackTrace();
			}
		}
	}

	@Override
	protected void finalize() throws Throwable {
		close();
	}
	
	
	@Override
	public void close() {
		Iterator<Connection> it = pool.iterator();
		while(it.hasNext()){
			try {
				it.next().close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		pool.clear();
	}

	
	
}
